package com.bmslz.monitor.base.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bmslz.monitor.base.entity.Project;
import com.bmslz.monitor.base.entity.ProjectData;
import com.bmslz.monitor.service.IProjectDataService;
import com.bmslz.monitor.service.IProjectService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName：OnlineJob
 * @Author: RuYuan Yang
 * @Date: 2025/9/6 14:36
 * @Description: 删除过期数据
 */
@Slf4j
@Component
public class ProjectDataTTLJob {
    @Autowired
    private IProjectDataService projectDataService;
    @Value("${sys.data.ttl}")
    private Integer ttl;//过期天数

    /**
     * @return void
     * @description: 每天执行一次删除过期的数据
     * @author: RuYuan Yang
     * @date 2025-11-11 14:47:39
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void executeTask() {
        try {
            log.info("开始执行过期数据清理任务，TTL: {} 天", ttl);

            if (ttl == null || ttl <= 0) {
                log.warn("TTL配置无效，默认为1");
                ttl = 1;
            }

            // 计算过期时间点
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -ttl);
            Date expireTime = calendar.getTime();

            // 构建查询条件：删除心跳时间早于过期时间的数据
            LambdaQueryWrapper<ProjectData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(ProjectData::getHeartTime, expireTime);

            // 执行删除操作
            boolean result = projectDataService.remove(queryWrapper);

            log.info("过期数据清理任务完成，删除状态: {}", result);

        } catch (Exception e) {
            log.error("执行过期数据清理任务时发生异常", e);
        }
    }
}
